package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Announcement;
import com.EAsystem.service.AnnouncementService;
import com.EAsystem.service.UserService;
import com.EAsystem.service.TeacherService;
import com.EAsystem.service.StudentService;
import com.EAsystem.service.CourseService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class AdminController {

    @Autowired
    private AnnouncementService announcementService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private CourseService courseService;

    @GetMapping("/home")
    public String adminHome(Model model) {

        // 获取统计数据
        List<com.EAsystem.entity.User> allUsers = userService.findAll();
        int adminCount = 0;
        if (allUsers != null) {
            for (com.EAsystem.entity.User user : allUsers) {
                if (user.getRole() == 1) { // 管理员角色
                    adminCount++;
                }
            }
        }
        
        PageInfo<com.EAsystem.entity.Teacher> teacherPageInfo = teacherService.findAllByPage(1, 1000); // 获取足够多的教师
        List<com.EAsystem.entity.Teacher> allTeachers = teacherPageInfo.getList();
        int teacherCount = allTeachers != null ? allTeachers.size() : 0;
        
        PageInfo<com.EAsystem.entity.Student> studentPageInfo = studentService.findAllByPage(1, 1000); // 获取足够多的学生
        List<com.EAsystem.entity.Student> allStudents = studentPageInfo.getList();
        int studentCount = allStudents != null ? allStudents.size() : 0;
        
        List<com.EAsystem.entity.Course> allCourses = courseService.findAll();
        int courseCount = allCourses != null ? allCourses.size() : 0;

        List<Announcement> academicNotifications = announcementService.findByTypeOne();
        List<Announcement> examNotifications = announcementService.findByTypeTwo();

        if (academicNotifications == null) {
            academicNotifications = new ArrayList<>();
        }
        if (examNotifications == null) {
            examNotifications = new ArrayList<>();
        }

        // 限制显示的通知数量
        if (academicNotifications.size() > 3) {
            academicNotifications = academicNotifications.subList(0, 3);
        }
        if (examNotifications.size() > 3) {
            examNotifications = examNotifications.subList(0, 3);
        }

        model.addAttribute("adminCount", adminCount);
        model.addAttribute("teacherCount", teacherCount);
        model.addAttribute("studentCount", studentCount);
        model.addAttribute("courseCount", courseCount);
        model.addAttribute("academicNotifications", academicNotifications);
        model.addAttribute("examNotifications", examNotifications);

        return "admin/home";
    }

    @GetMapping("/notifications/academic")
    public String listAcademicNotifications(@RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "5") int size,
                                            Model model,
                                            @RequestParam(required = false) String titleSearch) {


        PageInfo<Announcement> pageInfo;
        if (titleSearch != null && !titleSearch.isEmpty()) {
            Announcement announcement = new Announcement();
            announcement.setTitle(titleSearch);
            announcement.setType(1); // 教务通知类型
            pageInfo = announcementService.findByConditionPage(announcement, page, size);
        } else {
            pageInfo = announcementService.findByTypeOneWithPage(page, size);
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        model.addAttribute("announcements", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("titleSearch", titleSearch);

        return "admin/academic_notifications";
    }

    @PostMapping("/notifications/add")
    public String addNotification(Announcement announcement) {
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        announcement.setCreateTime(now);
        announcement.setUpdateTime(now);
        announcement.setStatus(1);
        announcementService.save(announcement);
        return "redirect:/admin/notifications/academic";
    }

    // 单条删除
    @GetMapping("/notifications/delete/{id}")
    public String deleteNotification(@PathVariable Integer id) {
        announcementService.delete(id);
        return "redirect:/admin/notifications/academic";
    }

    // 批量删除
    @GetMapping("/notifications/batchDelete")
    public String batchDelete(@RequestParam("ids") String ids) {
        for (String id : ids.split(",")) {
            announcementService.delete(Integer.valueOf(id));
        }
        return "redirect:/admin/notifications/academic";
    }

    // 查询单条通知（用于编辑时回显）
    @GetMapping("/notifications/view/{id}")
    @ResponseBody
    public Announcement viewNotification(@PathVariable Integer id) {
        Announcement a = announcementService.findById(id);
        if (a == null) throw new RuntimeException("未找到该公告");
        return a;
    }

    // 编辑保存
    @PostMapping("/notifications/edit")
    public String editNotification(Announcement announcement) {
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        announcement.setUpdateTime(now);
        announcementService.edit(announcement.getId(), announcement.getTitle(), announcement.getContent(), announcement.getType(), announcement.getUpdateTime());
        return "redirect:/admin/notifications/academic";
    }
}